package com.lyh.hkcloud.service;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.activity.HomeActivity;
import com.lyh.hkcloud.constants.AssetManagementConstants;
import com.lyh.hkcloud.constants.HttpUrlComstants;
import com.lyh.hkcloud.util.base.*;
import com.lyh.hkcloud.util.http.listener.json.JsonFailuredListener;
import com.lyh.hkcloud.util.http.listener.json.JsonSuccessListener;
import com.lyh.hkcloud.util.http.Request;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class UserService {

    private Activity activity;

    public UserService(Activity activity) {
        this.activity = activity;
    }

    public void verification(String userName, String password, final JsonSuccessListener successListener, final JsonFailuredListener failuredListener) {

        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            ToastUtils.makeText(activity, "请输入帐号/密码！", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("userName", userName);
            jsonObject.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Request.post(activity, "UrlConstants.BASE_URL" + "/eip-mapp-umc-server/user/login", jsonObject, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                if (!"0000".equals(response.optString("code"))) {
                    failuredListener.onRespone(response.optString("msg"), response);
                    //ToastUtils.makeText(activity, response.optString("msg"), ToastUtils.LENGTH_SHORT).show();
                } else {
                    JSONObject data = response.optJSONObject("data");
                    successListener.onRespone("", data);
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
                failuredListener.onRespone(msg, response);
                //ToastUtils.makeText(activity, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });

    }

    public void modifyPassword(final String userName) {
        View layout = View.inflate(activity, R.layout.dialog_modify_password, null);
        final EditText oldPassword = layout.findViewById(R.id.et_oldPassword);
        final EditText newPassword = layout.findViewById(R.id.et_newPassword);
        final EditText confirmPassword = layout.findViewById(R.id.et_confirmPassword);
        oldPassword.setFocusable(true);
        new AlertDialog.Builder(activity).setTitle("修改密码").setView(layout).setIcon(R.drawable.modify_pwd)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        modifyPassword(userName, oldPassword.getText().toString(), newPassword.getText().toString(), confirmPassword.getText().toString(), new JsonFailuredListener() {
                            @Override
                            public void onRespone(String msg, JSONObject response) {
                                ToastUtils.makeText(activity, msg, ToastUtils.LENGTH_SHORT).show();
                            }
                        });
                    }
                })
                .setNegativeButton("取消", null).setCancelable(false).show();
        oldPassword.requestFocus();
    }

    /**
     * 登录
     * @param loginMode 登录方式
     * @param userName	用户名
     * @param password	密码
     * @param successActivity 	成功
     * @param failActivity 失败
     * @return void
     * @author: zhongfan
     * @Date 2022/2/10 14:44
    **/
    public void login(final String loginMode,final String userName, String password, final Class successActivity, final Class failActivity,final JsonSuccessListener successListener) {
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            ToastUtils.makeText(activity, "请输入用户名/密码！", ToastUtils.LENGTH_SHORT).show();
            return;
        }

        SaveData.putValue(activity,"token",null);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("account", userName);
            jsonObject.put("password", password);
        } catch (Exception e) {
            Log.e("获取用户名/密码错误",e.getMessage(),e);
        }

        Request.post(activity, HttpUrlComstants.DOMAIN_NAME_URL + loginMode, jsonObject, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                LogUtil.i("",response.toString());
                try {
                    if (StringUtils.responseResults(response)) {
                        String token ="";
                        if(loginMode.equals(HttpUrlComstants.ENTERPRISE)){
                            token = response.getJSONObject("data").getString("token");
                        }else{
                            token = response.getString("data");
                        }
                        String[] split = token.split("=");
                        if (split.length == 2) {
                            SaveData.putValue(activity,"token",split[1]);
                        }else{
                            SaveData.putValue(activity,"token",token);
                        }

                        SaveData.putValue(activity,"username",userName);
                        SaveData.putValue(activity,"password",password);

                        //资产管理系统的商户id
                        jsonObject.put("merchantId", AssetManagementConstants.PRODUCTION_MERCHANT_ID);
                        getUserInfo(jsonObject, successActivity,  failActivity,successListener);


                    }else{
                        LoadingUtils.getInstance(activity).hide();
                        ToastUtils.makeText(activity, "登录失败："+response.get("message").toString(), ToastUtils.LENGTH_LONG).show();
                        if (failActivity != activity.getClass()) {
                            activity.startActivity(new Intent(activity, failActivity));
                            activity.finish();
                        }
                    }
                } catch (JSONException e) {
                   Log.e("获取响应信息失败",e.getMessage(),e);
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                if (response != null) {
                    Log.e("error",response.optString("message"));
                    LoadingUtils.getInstance(activity).hide();
                    ToastUtils.makeText(activity, response.toString(), ToastUtils.LENGTH_SHORT).show();
                }

            }
        });
    }

    public void getUserInfo(JSONObject jsonObject,final Class successActivity, final Class failActivity, final JsonSuccessListener successListener) {

        Request.post(activity, HttpUrlComstants.DOMAIN_NAME_URL + HttpUrlComstants.userInfo, jsonObject, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                if (!"0000".equals(response.optString("code"))) {
                    LoadingUtils.getInstance(activity).hide();
                    Log.e("error","请求getUserInfo错误");
                    ToastUtils.makeText(activity, "请求getUserInfo错误:"+response.optString("message"), ToastUtils.LENGTH_SHORT).show();
                    activity.startActivity(new Intent(activity, failActivity));
                    activity.finish();
                } else {
                    /*Toast.makeText(activity, "登录成功", Toast.LENGTH_SHORT).show();*/
                    try {
                        SaveData.putValue(activity,"userid",response.getJSONObject("data").get("userId").toString());
                        SaveData.putValue(activity,"employeeNo",response.getJSONObject("data").get("employeeNo").toString());
                        SaveData.putValue(activity,"userName",response.getJSONObject("data").get("userName").toString());
                        JSONArray deptList=response.getJSONObject("data").getJSONArray("deptList");
                        String userDept=deptList.length()>0?deptList.getJSONObject(0).getString("organizationName"):"";
                        SaveData.putValue(activity,"userDept",userDept);
                        SaveData.putValue(activity,"roleList",response.getJSONObject("data").get("roleList").toString());

                        Intent intent = new Intent(activity, HomeActivity.class);
                        activity.startActivity(intent);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new JsonFailuredListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                Log.e("error",response.optString("message"));
                LoadingUtils.getInstance(activity).hide();
                ToastUtils.makeText(activity, msg, ToastUtils.LENGTH_SHORT).show();
            }
        });
    }

    public void modifyPassword(String userName, String oldPassword, String newPassword, String confirmPassword, final JsonFailuredListener failuredListener) {
        if (ConvertUtil.isEmpty(oldPassword)) {
            failuredListener.onRespone("请输入原密码!", null);
            return;
        }
        if (ConvertUtil.isEmpty(newPassword)) {
            failuredListener.onRespone("请输入新密码!", null);
            return;
        }
        if (!newPassword.equals(confirmPassword)) {
            failuredListener.onRespone("新密码与确认密码不一致!", null);
            return;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("oldPassword", oldPassword);
            jsonObject.put("newPassword", newPassword);
            jsonObject.put("password", newPassword);
            jsonObject.put("userName", userName);
            jsonObject.put("type", "initPwd");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = StringUtils.isEmpty(userName) ? "/eip-mapp-cmc-server/user/updPassword" : "/eip-mapp-cmc-server/user/updInitPassword";
        Request.post(activity, "UrlConstants.BASE_URL" + url, jsonObject, new JsonSuccessListener() {
            @Override
            public void onRespone(String msg, JSONObject response) {
                if (!"0000".equals(response.optString("code"))) {
                    failuredListener.onRespone(response.optString("msg"), null);
                } else {
                    ToastUtils.makeText(activity, "密码修改成功", ToastUtils.LENGTH_SHORT).show();
                }
            }
        }, failuredListener);
    }

}
